﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Tms.Biz;
using Tms.Model;
using Util.Common;
using WPF.Controls;

namespace Tms.Double.WPFApp
{
    /// <summary>
    /// ManagerEditWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ManagerEditWindow : Window
    {
        //传参
        public Model.manager oriManager = null;
        
        //--------------------------------------------------------------------------------------------

        public ManagerEditWindow()
        {
            InitializeComponent();
        }
        
        //Loaded--初始
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //隐藏
            ckSys.Visibility = Visibility.Hidden;     //隐藏，系统管理员角色，暂不用 
            TxtId.Visibility = Visibility.Hidden;     //隐藏，但有用
            TxtSalt.Visibility = Visibility.Hidden;   //隐藏，但有用
            TxtUserName_Ori.Visibility = Visibility.Hidden;   //隐藏，但有用
            
            //
            ToUI();
        }

        private void ToUI()
        {
            if (oriManager == null)
            {
                return;
            }

            TxtId.Text = oriManager.id.ToString();
            TxtSalt.Text = oriManager.salt;
            TxtUserName_Ori.Text = oriManager.user_name;

            TxtUserName.Text = oriManager.user_name;
            TxtRealName.Text = oriManager.real_name;
            TxtTelephone.Text = oriManager.telephone;
            TxtEmail.Text = oriManager.email;

            TxtPassword.Password = "";
            if (!string.IsNullOrEmpty(oriManager.password) && !string.IsNullOrEmpty(oriManager.salt))
            {
                TxtPassword.Password = DESEncrypt.Decrypt(oriManager.password, oriManager.salt);
            }
            TxtPassword2.Password = TxtPassword.Password;

            if (oriManager.is_lock == 0)
                ckIsLock.IsChecked = false;
            else if (oriManager.is_lock == 1)
                ckIsLock.IsChecked = true;

            ClearRoleTypeCheckBox();
            if (oriManager.role_type == (int)Model.RoleTypeEnum.admin)
                ckAdmin.IsChecked = true;
            else if (oriManager.role_type == (int)Model.RoleTypeEnum.guest)
                ckGuest.IsChecked = true;
            else if (oriManager.role_type == (int)Model.RoleTypeEnum.sys)
                ckSys.IsChecked = true;
            else if (oriManager.role_type == (int)Model.RoleTypeEnum.nomal)
                ckNomal.IsChecked = true;

            TxtDeptName.Text = oriManager.dept_name;
            TxtDoctorName.Text = oriManager.doctor_name;
        }

        #region 标题栏

        //最小化窗口
        private void BtnMinWindow_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        //关闭窗口
        private void BtnCloseWindow_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //允许窗口拖动
        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)  //过滤掉双击
            {
                //允许窗口拖动
                this.DragMove();
            }
        }

        #endregion

        #region 界面

        //界面--双击清空
        private void TxtBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TextBox txt = sender as TextBox;
            txt.Text = "";  //清
        }
        private void PwdBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            PasswordBox pwd = sender as PasswordBox;
            pwd.Password = "";  //清
        }

        //界面--权限类型只能选一个
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            CheckBox box = sender as CheckBox;
            if (box.IsChecked == true)
            {
                if (box.Name == "ckAdmin")
                {
                    ckGuest.IsChecked = false;
                    ckSys.IsChecked = false;
                    ckNomal.IsChecked = false;
                }
                else if (box.Name == "ckGuest")
                {
                    ckAdmin.IsChecked = false;
                    ckSys.IsChecked = false;
                    ckNomal.IsChecked = false;
                }
                else if (box.Name == "ckSys")
                {
                    ckAdmin.IsChecked = false;
                    ckGuest.IsChecked = false;
                    ckNomal.IsChecked = false;
                }
                else if (box.Name == "ckNomal")
                {
                    ckAdmin.IsChecked = false;
                    ckGuest.IsChecked = false;
                    ckSys.IsChecked = false;
                }
            }
        }

        //界面--是否锁定
        private void ckIsLock_Click(object sender, RoutedEventArgs e)
        {

        }
        //界面--清编辑区
        private void ClearEditingArea()
        {
            TxtId.Text = "";
            TxtSalt.Text = "";
            TxtUserName_Ori.Text = "";

            TxtUserName.Text = "";
            TxtRealName.Text = "";
            TxtTelephone.Text = "";
            TxtEmail.Text = "";
            TxtPassword.Password = "";
            TxtPassword2.Password = "";
            ckIsLock.IsChecked = false;
            ClearRoleTypeCheckBox();  
            
            TxtDeptName.Text = "";
            TxtDoctorName.Text = "";
        }
        //界面--清权限类型
        private void ClearRoleTypeCheckBox()
        {
            ckAdmin.IsChecked = false;
            ckGuest.IsChecked = false;
            ckSys.IsChecked = false;
            ckNomal.IsChecked = false;
        }
        //界面--权限类型已选数量
        private int RoleTypeCheckedCount()
        {
            int n = 0;
            if (ckAdmin.IsChecked == true) n++;
            if (ckGuest.IsChecked == true) n++;
            if (ckSys.IsChecked == true) n++;
            if (ckNomal.IsChecked == true) n++;

            return n;
        }

        //界面--确认密码--暂不用
        private void TxtPassword2_LostFocus(object sender, RoutedEventArgs e)
        {
            ////if (string.IsNullOrEmpty(TxtPassword.Password.Trim()))
            ////{
            ////    MessageBoxX.Warning("密码不能为空！", this);
            ////    return;
            ////}
            ////if (string.IsNullOrEmpty(TxtPassword2.Password.Trim()))
            ////{
            ////    MessageBoxX.Warning("确认密码不能为空！", this);
            ////    return;
            ////}
            ////if (TxtPassword.Password.Trim() != TxtPassword2.Password.Trim())
            ////{
            ////    MessageBoxX.Warning("确认密码与密码不一致！", this);
            ////    return;
            ////}
        }

        #endregion

        //FromUI
        private Model.manager FromUI()
        {
            Model.manager model = new Model.manager();

            model.id = Convert.ToInt32(TxtId.Text.Trim());

            model.user_name = TxtUserName.Text.Trim();
            model.real_name = TxtRealName.Text.Trim();
            model.telephone = TxtTelephone.Text.Trim();
            model.email = TxtEmail.Text.Trim();

            //空密码（即''）也可以通过 salt 加密 
            model.salt = TxtSalt.Text.Trim();            
            model.password = DESEncrypt.Encrypt(TxtPassword.Password.Trim(), model.salt);

            model.is_lock = 0;
            if (ckIsLock.IsChecked == true) model.is_lock = 1;

            model.role_type = (int)Model.RoleTypeEnum.nomal;
            if (ckAdmin.IsChecked == true) model.role_type = (int)Model.RoleTypeEnum.admin;
            else if (ckGuest.IsChecked == true) model.role_type = (int)Model.RoleTypeEnum.guest;
            else if (ckSys.IsChecked == true) model.role_type = (int)Model.RoleTypeEnum.sys;

            model.add_time = DateTime.Now;

            model.dept_name = TxtDeptName.Text.Trim();
            model.doctor_name = TxtDoctorName.Text.Trim();

            return model;
        }
        
        //修改
        private void BtnEdit_Click(object sender, RoutedEventArgs e)
        {
            BLL.manager bll = new BLL.manager();

            #region 校验

            if (string.IsNullOrEmpty(TxtUserName.Text.Trim()))
            {
                MessageBoxX.Warning("用户名不能为空！", this);
                return;
            }
                        
            ////if (string.IsNullOrEmpty(TxtPassword.Password.Trim()))
            ////{
            ////    MessageBoxX.Warning("密码不能为空！", this);
            ////    return;
            ////}
            ////if (string.IsNullOrEmpty(TxtPassword2.Password.Trim()))
            ////{
            ////    MessageBoxX.Warning("确认密码不能为空！", this);
            ////    return;
            ////}
            if (TxtPassword.Password.Trim() != TxtPassword2.Password.Trim())
            {
                MessageBoxX.Warning("确认密码与密码不一致！", this);
                return;
            }

            int n = RoleTypeCheckedCount();
            if (n == 0)
            {
                MessageBoxX.Warning("请选择一个权限类型", this);
                return;
            }
            else if (n > 1)
            {
                MessageBoxX.Warning("只能选择一个权限类型", this);
                return;
            }

            if (ckNomal.IsChecked != null && ckNomal.IsChecked == true && string.IsNullOrEmpty(TxtDoctorName.Text.Trim()))
            {
                MessageBoxX.Warning("医生姓名不能为空！", this);
                return;
            }

            if (TxtUserName.Text.Trim() != TxtUserName_Ori.Text.Trim())
            {
                bool be = bll.Exists(TxtUserName.Text.Trim());
                if (be)
                {
                    MessageBoxX.Warning("该【用户名称】已存在，修改失败！", this);
                    return;
                }
            }

            #endregion

            //
            if (string.IsNullOrEmpty(TxtSalt.Text.Trim()))
            {
                TxtSalt.Text = GlobalBiz.GenSalt();//6位随机字符串 //因为空，所以重新生成。
            }

            //修改
            Model.manager newManager = FromUI();            
            bool b = bll.Update(newManager);
            if (!b)
            {
                MessageBoxX.Info("修改失败！", this);
                return;                
            }

            //同步更新缓存
            if(newManager.id == GlobalCache.User.id)  //OK
            {
                //
                GlobalCache.User = newManager;

                //20210525 同步
                if ((oriManager.user_name != newManager.user_name) ||
                    (oriManager.doctor_name != newManager.doctor_name))
                {
                    if(GlobalCache.g_patient.user_name == oriManager.user_name)
                    {
                        GlobalCache.g_patient.user_name = GlobalCache.User.user_name;//20210525 同步
                        GlobalCache.g_patient.doctor_name = GlobalCache.User.doctor_name;//20210525 同步

                        (new BLL.patient()).UpdateDoctorName(GlobalCache.g_patient);//20210525 同步

                        //清方案缓存 //20210525 同步
                        GlobalCache.g_CoilParaColl.Clear();
                        GlobalCache.g_patient_plan.Clear2();
                        GlobalCache.g_patient_tbsplan.Clear2();
                    }
                }
            }
                        
            //关闭
            this.DialogResult = true;
            this.Close();

        }
        
        //取消
        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            //关闭
            this.DialogResult = false;
            this.Close();
        }

        //清编辑区
        private void BtnClearEditing_Click(object sender, RoutedEventArgs e)
        {
            ClearEditingArea();
        }

    }
}
